package com.example.rabbitmqbootproducer.service.impl;

import com.example.rabbitmqbootproducer.dto.MessageDTO;
import com.example.rabbitmqbootproducer.service.SendMessageService;
import com.google.gson.Gson;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

import static com.example.rabbitmqbootproducer.constant.MessageConstant.*;

/**
 * 发送消息实现类
 *
 * @author 伯路平
 * @since 2023/6/19
 **/
@Service
@RequiredArgsConstructor
public class SendMessageServiceImpl implements SendMessageService {
    private final RabbitTemplate rabbitTemplate;
    private static final Gson GSON = new Gson();

    @Override
    public void sendDirectMessage(MessageDTO messageDTO) {
        for (int i = 0; i < 10; i++) {
            messageDTO.setMessageId(UUID.randomUUID().toString());
            String message = GSON.toJson(messageDTO);
            rabbitTemplate.convertAndSend(DIRECT_EXCHANGE_NAME, DIRECT_ROUTING_KEY, message);
        }
    }

    @Override
    public void sendFanoutMessage(MessageDTO messageDTO) {
        for (int i = 0; i < 10; i++) {
            messageDTO.setMessageId(UUID.randomUUID().toString());
            String message = GSON.toJson(messageDTO);
            rabbitTemplate.convertAndSend(FANOUT_EXCHANGE_NAME, "", message);
        }
    }

    @Override
    public void sendNotExistExchange(MessageDTO messageDTO) {
        messageDTO.setMessageId(UUID.randomUUID().toString());
        String message = GSON.toJson(messageDTO);
        rabbitTemplate.convertAndSend("not-exist-exchange", "", message);
    }

    @Override
    public void notBindingQueue(MessageDTO messageDTO) {
        messageDTO.setMessageId(UUID.randomUUID().toString());
        String message = GSON.toJson(messageDTO);
        rabbitTemplate.convertAndSend(TEST_CALLBACK_EXCHANGE_NAME, "", message);
    }

    @Override
    public void errorBindingQueue(MessageDTO messageDTO) {
        messageDTO.setMessageId(UUID.randomUUID().toString());
        String message = GSON.toJson(messageDTO);
        rabbitTemplate.convertAndSend(TEST_ERROR_BINDING_EXCHANGE_NAME, "errorRoutingKey", message);
    }

    @Override
    public void expiredQueue(MessageDTO messageDTO) {
        messageDTO.setMessageId(UUID.randomUUID().toString());
        String message = GSON.toJson(messageDTO);
        rabbitTemplate.convertAndSend(DIRECT_EXCHANGE_NAME, DIRECT_EXPIRED_ROUTING_KEY, message);
    }
}
